import {Component, OnInit} from '@angular/core';
import {AsyncValidatorFn, FormBuilder, FormControl, FormGroup, ValidationErrors} from '@angular/forms';
import {HttpClient} from '@angular/common/http';
import {catchError, debounceTime, distinctUntilChanged, first, map, mergeMap, switchMap} from 'rxjs/operators';
import {Observable, of} from 'rxjs';

@Component({
  selector: 'app-third-validation',
  templateUrl: './third-validation.component.html',
  styleUrls: ['./third-validation.component.css']
})
export class ThirdValidationComponent implements OnInit {

  form: FormGroup;
  fieldBase: any[];
  formTemplateXml = `[
  {
    "name": "申请金额",
    "id": "text",
    "required": true,
    "isMultiple": false,
    "type": "text",
    "value": "",
    "validate": "7",
    "validatorSource": "http://localhost:8080/validate?money="
  }
]`;

  constructor(private fb: FormBuilder,
              private http: HttpClient) {
  }

  ngOnInit() {
    this.form = this.fb.group({});
    this.fieldBase = JSON.parse(this.formTemplateXml);
    this.fieldBase.forEach(field => {
      if (field.validate === '7') {
        this.form.addControl(field.id,
          this.fb.control(field.value, {updateOn: 'blur'}));
        this.form.controls[field.id].setAsyncValidators(this.thirdApiValidator(field.validatorSource));
      }
    });

    setInterval(() => {
      console.log(this.form);
    }, 2000);
  }

  thirdApiValidator(url: string): AsyncValidatorFn {
    return (control: FormControl): Observable<ValidationErrors | null> => {
      return control.valueChanges.pipe(
        distinctUntilChanged(),
        debounceTime(400),
        switchMap(() => this.isValidate(control.value, url)),
        map(res => {
          return res.success ? null : {message: res.message};
        }),
        first()
      );
    };
  }

  isValidate(value: any, url: string): Observable<any> {
    return this.http.get(url + value);
  }

}
